package com.ustb.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ustb.springboot.common.utils.R;
import com.ustb.springboot.common.utils.TokenUtil;
import com.ustb.springboot.dao.AnswerScoreDao;
import com.ustb.springboot.entity.AnswerBlankEntity;
import com.ustb.springboot.entity.AnswerScoreEntity;
import com.ustb.springboot.entity.QuestionScoreEntity;
import com.ustb.springboot.service.AnswerScoreService;
import com.ustb.springboot.service.QuestionScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("answerScoreService")
public class AnswerScoreServiceImpl extends ServiceImpl<AnswerScoreDao, AnswerScoreEntity> implements AnswerScoreService {

    @Resource
    private AnswerScoreDao answerScoreDao;

    @Autowired
    private QuestionScoreService questionScoreService;

    @Override
    public R save(HttpServletRequest request, AnswerScoreEntity answerScoreEntity) {
        //设置userId
        answerScoreEntity.setUserId(TokenUtil.getId(request));

        //保存成功或失败
        return this.saveOrUpdate(answerScoreEntity) ? R.ok(20000, "保存填空题答案成功！") : R.error(2000, "保存填空题答案失败！");
    }

    @Override
    public R delete(Map<String, Object> body) {
        //根据id查询删除
        QueryWrapper<AnswerScoreEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", body.get("id"));
        return answerScoreDao.delete(queryWrapper) == 1 ? R.ok(20000, "删除成功！") : R.error(2000, "删除失败！");
    }

    @Override
    public List<AnswerScoreEntity> queryAnswerScoreWithQuestionId(Map<String, Object> body) {
        QueryWrapper<AnswerScoreEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("question_id", body.get("question_id"));
        return answerScoreDao.selectList(queryWrapper);
    }

    @Override
    public Map<String, Object> summerize(Map<String, Object> body) {
        List <AnswerScoreEntity> answerScoreEntityList = queryAnswerScoreWithQuestionId(body);
        List <QuestionScoreEntity> questionScoreEntityList = questionScoreService.queryQuestionScore(body);
        List<Object> TotalMessage = new ArrayList<>();
        for (AnswerScoreEntity answerScore : answerScoreEntityList){
            List<Object> message = new ArrayList<>();
            message.add(answerScore.getAnswer());
            TotalMessage.add(message);
        }
        Map<String,Object> summerizeMessage =new HashMap<>();
        summerizeMessage.put("totalMessage",TotalMessage);
        summerizeMessage.put("sum",answerScoreEntityList.size());
        return summerizeMessage;
//        return null;
    }
}